package com.heima.admin.gateway.filter;

import com.heima.common.dtos.Payload;
import com.heima.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter {
    /**
     * 拦截请求
     * 判断是否放行
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        获取request对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//        获取请求路径
        String path = request.getURI().getPath();
        log.info("path=={}",path);
//        判断是否登录请求
        if(path.contains("/login/in")) {
//        如果是登录，直接放行
            return chain.filter(exchange);
        }
//        从请求头获取token
        String token = request.getHeaders().getFirst("token");
//        判断token是否存在
        if(StringUtils.isBlank(token)){
            log.error("token不存在");
//        如果token不存在，结束，返回未登录状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        验证token
        try {
            Payload payload = JwtUtils.getInfoFromToken(token);
            Integer userId = payload.getUserId();
//            把userId 放入请求头中,返回新的request请求
            ServerHttpRequest httpRequest= request.mutate()
                    .header("userId", userId.toString())
                    .build();
            exchange.mutate().request(httpRequest);
        }catch (Exception e){
            //        如果验证不通过，结束
            log.error("token验证不通过");
//        如果token不存在，结束，返回未登录状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        log.info("请求放行=====");
//        如果验证通过，就放行
        return chain.filter(exchange);
    }
}
